<?php
/*
 * @Author: lokei
 * @Date: 2022-08-09 07:54:05
 * @LastEditors: lokei
 * @LastEditTime: 2023-07-04 08:56:35
 * @Description: 
 */

namespace App\Common\Tools;

class IpTool
{
	public static function getRealIp()
	{

		$ip = data_get($_SERVER, 'HTTP_X_FORWARDED_FOR'); #获取用户ip
		if (strstr($ip, ",")) { #如果经过代理有多个ip,循环处理
			$ip_arr = explode(',', $ip);
			foreach ($ip_arr as $ip) {
				$ipint = sprintf('%u', ip2long($ip)); #ip2long — 将 IPV4 的字符串互联网协议转换成长整型数字
				if (
					$ipint >= 0 && $ipint <= 50331647 || // {"0.0.0.0","2.255.255.255"},
					$ipint >= 167772160 && $ipint <= 184549375 || // {"10.0.0.0","10.255.255.255"},
					$ipint >= 2130706432 && $ipint <= 2147483647 || // {"127.0.0.0","127.255.255.255"},
					$ipint >= 2851995648 && $ipint <= 2852061183 || // {"169.254.0.0","169.254.255.255"}
					$ipint >= 2886729728 && $ipint <= 2887778303 || // {"172.16.0.0","172.31.255.255"},
					$ipint >= 3221225984 && $ipint <= 3221226239 || // {"192.0.2.0","192.0.2.255"},
					$ipint >= 3232235520 && $ipint <= 3232301055 || // {"192.168.0.0","192.168.255.255"},
					$ipint >= 4294967040 && $ipint <= 4294967295 // {"255.255.255.0","255.255.255.255"}
				) {
					continue;
				} else {
					break;
				}
			}
		}
		if ($ip != '') {
			return trim($ip);
		} else {
			return request()->ip();
		}
	}
}
